<template>
  <div>
    <!-- 导航栏部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 主体部分 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoles()">添加角色</el-button>
        </el-col>
      </el-row>

      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="[
                'borderBottom',
                'vcenter',
                index1 === 0 ? 'borderTop' : '',
              ]"
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  type="primary"
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二、三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :class="['vcenter', index2 === 0 ? '' : 'borderTop']"
                  :key="item2.id"
                >
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, index3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <!-- 顺序列 -->
        <el-table-column type="index"> </el-table-column>
        <el-table-column label="角色名称" prop="roleName"> </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope" width="300px">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRoles(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoles(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限页面 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClose()"
    >
      <el-tree
        :data="rightsList"
        :props="rightsProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="ThreeIdKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="assigRights()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色页面 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialogVisible"
      width="50%"
    >
      <el-form
        :model="addRolesRuleForm"
        :rules="addRolesRules"
        ref="addRolesRuleRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesRuleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesRuleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolesDialog()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色页面 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRolesDialogVisible"
      width="50%"
    >
      <el-form
        :model="editRolesRuleForm"
        :rules="editRolesRules"
        ref="editRolesRuleRef"
        label-width="150px"
      >
        <el-form-item label="请修改角色名称" prop="roleName">
          <el-input v-model="editRolesRuleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="请修改角色描述" prop="roleDesc">
          <el-input v-model="editRolesRuleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesDialog()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
name:'',
  data() {
    //验证角色名称规则
    const checkRoleName=(rule, value, callback)=>{
      const regRoleName=/[^~\x22]+/;
      if(regRoleName.test(value)){
        return callback();
      }else{
        return callback(new Error('请输入正确的角色名称'));
      };
    };
    //验证角色描述规则
    const checkRoleDesc=(rule, value, callback)=>{
      const regRoleDesc=/[^~\x22]+/;
      if(regRoleDesc.test(value)){
        return callback();
      }else{
        return callback(new Error('请输入正确的角色描述'));
      };
    };
   
    return {
        rolesList:[],
        setRightDialogVisible:false,
        rightsList:[],
        rightsProps:{
          children: 'children',
          label: 'authName',
        },
        //三级权限的id数组
        ThreeIdKeys:[],
        //选中角色的id
        roleId:'',
        //添加角色页面的是否打开
        addRolesDialogVisible:false,
        //添加角色页面的表格
        addRolesRuleForm:{
          //角色名称
          roleName:'',
          //角色描述
          roleDesc:'',
        },
        //添加角色页面的规则
        addRolesRules:{
          //角色名称规则
          roleName: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { validator: checkRoleName, trigger: 'blur' }
          ],
          //角色描述规则
          roleDesc: [
            { required: true, message: '请输入角色描述', trigger: 'blur' },
            { validator: checkRoleDesc, trigger: 'blur' }
          ],
        },
        //编辑角色页面的是否打开
        editRolesDialogVisible:false,
        //编辑角色的表格
        editRolesRuleForm:{
          //角色名称
          roleName:'',
          //角色描述
          roleDesc:'',
        },
        //编辑角色页面的规则
        editRolesRules:{
          //角色名称规则
          roleName: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { validator: checkRoleName, trigger: 'blur' }
          ],
          //角色描述规则
          roleDesc: [
            { required: true, message: '请输入角色描述', trigger: 'blur' },
            { validator: checkRoleDesc, trigger: 'blur' }
          ],
        },
    }
  },
  created(){
      this.getRolesList()
  },
  methods:{
      //获取角色列表
      async getRolesList(){
          const {data:res}=await this.$http.get('/roles');
          if(res.meta.status!==200) return this.$message.error('获取权限列表失败');
          this.rolesList=res.data;
      },
      //删除三级权限
      async removeRightById(roles,rights){
        const result= await this.$confirm('此操作将永久删除此权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err);

        if(result!=='confirm') return this.$message('取消删除');

        const {data:res}=await this.$http.delete(`roles/${roles.id}/rights/${rights}`);
        if(res.meta.status!==200) return this.$message('删除失败');
        this.$message({
          message: '删除成功',
          type: 'success'
        });

        roles.children=res.data;
      },
      //打开分配权限页面
      async showSetRightDialog(node){
        this.roleId=node.id;
        const {data:res}=await this.$http.get('/rights/tree');
        if(res.meta.status!=200) return this.$message.error('获取权限失败');
        this.rightsList=res.data;
        // console.log(this.rightsList);
        //获取三级权限id
        this.getthreeIdKeys(node,this.ThreeIdKeys)
        //打开页面
        this.setRightDialogVisible=true;
      },
      //获取三级权限id
      getthreeIdKeys(node,arr){
        //如果是三级，则加入该节点的id
        if(!node.children) return arr.push(node.id);
        //循环遍历数组
        node.children.forEach(element => {
          this.getthreeIdKeys(element,arr);
        });
      },
      //关闭分配权限页面
      setRightDialogClose(){
        this.ThreeIdKeys=[]
      },
      //确认分配权限
      async assigRights(){
        //获得所有选中的和其父类的id值
        const key=[...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()];
        const rids=key.join(',');
        //发送请求
        const {data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:rids});
        if(res.meta.status!=200) return this.$message.error('分配权限失败');
        this.$message({
          message: '分配权限成功',
          type: 'success'
        });
        //关闭分配权限页面
        this.setRightDialogVisible = false
        //重新渲染列表
        this.getRolesList();
      },
      //添加角色
      async addRoles(){
        this.addRolesDialogVisible=true;
      },
      //确认添加角色
      addRolesDialog(){
        //符合规则后
        this.$refs['addRolesRuleRef'].validate(async (valid) => {
        if (valid) {
          //发送请求
          const {data:res}=await this.$http.post('roles',{roleName:this.addRolesRuleForm.roleName,roleDesc:this.addRolesRuleForm.roleDesc});
          //创建失败
          if(res.meta.status!=201) return this.$message.error('分配权限失败');
          //创建成功
          this.$message({
          showClose: true,
          message: '创建角色成功',
          type: 'success'
          });
          //关闭对话框
          this.addRolesDialogVisible = false;
          //重新获取列表数据
          this.getRolesList();
        } else {
          return false
        }
      })
        this.addRolesDialogVisible=false;
      },
      //删除角色
      async deleteRoles(ID){
        const result= await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err);
        //点击取消
        if(result!='confirm'){
          return this.$message({
            type: 'info',
            message: '已取消删除'
          });   
        }else{
        //点击确认
        const {data:res}=await this.$http.delete(`roles/${ID}`);
        if(res.meta.status!==200) this.$message.error('删除角色失败');
        //删除角色成功
        this.$message({
        showClose: true,
        message: '删除角色成功',
        type: 'success'
        });
        //重新获取列表数据
        this.getRolesList();
        }
        
      },
      //编辑提交角色
      editRoles(scope){
        this.editRolesDialogVisible=true;
        //将当前角色的属性传到编辑角色的属性上
        this.editRolesRuleForm=scope;
      },
      //确认编辑角色
      editRolesDialog(){
        this.$refs.editRolesRuleRef.validate(async (valid)=>{
          if(valid){
            //发送请求
            const {data:res}=await this.$http.put(`roles/${this.editRolesRuleForm.id}`,{
              roleName:this.editRolesRuleForm.roleName,
              roleDesc:this.editRolesRuleForm.roleDesc
            });
            this.$message({
            showClose: true,
            message: '编辑角色成功',
            type: 'success'
            });
            if(res.meta.status!=200) return this.$message.error('编辑角色失败');
            //刷新页面
            this.getRolesList();
            //关闭窗口
            this.editRolesDialogVisible=false;
          }
          return false;
        })  
      }
  },
  components: {

  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.borderTop {
  border-top: 1px solid #e9edf1;
}
.borderBottom {
  border-bottom: 1px solid #e9edf1;
}
</style>

